package tianwang.utils.dict;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class DictionaryImplBase implements Dictionary {
	
	
	/**
	 * 词典
	 * 
	 * Map<单词(小写形式)，整个词条>
	 */
	protected Map<String, Entry> dict = null;
	
	/**
	 * 词典的大小
	 * 
	 * 避免词条个数多而引发的Map性能问题
	 */
	protected int dictionarySize;
	
	/**
	 * 词典文件保存的路径
	 */
	protected String corpusPath;
	
	/**
	 * 词典条目模板
	 * 
	 * 如keySet ：“单词”，“词性”等
	 * 
	 * Map<"单词"等，位置0,1...>
	 */
	protected Map<String, Integer> entryTemplate = null;
	
	/**
	 * 词条生成器
	 * 将词典文件加载到模板中
	 */
	protected EntryProcesser entryProcesser = null;

	
	public boolean contains(String entry) {
		if ( dict == null ){
			return false;
		}
		return dict.keySet().contains(entry);
	}

	public void initial() {
		
		if ( dict != null) return;
		if ( entryTemplate == null ){
			return;
		}
		
		dict = new HashMap<String, Entry>(dictionarySize);
		entryProcesser.setEntryTemplate(entryTemplate);
		
		InputStream is = null;
		BufferedReader br = null;		
		try {
			is = this.getClass().getResourceAsStream(corpusPath);
			br = new BufferedReader(new InputStreamReader(is));
			String tmp;
			while((tmp=br.readLine())!=null){
				if(tmp.startsWith("//")){//注释行
					continue;
				}
				
				Entry entry = entryProcesser.process(tmp);
				dict.put(entry.getLowerCoreWord(), entry);
			}
		} catch (FileNotFoundException e) {
			br=null;
			dict = null;
			e.printStackTrace();
		} catch (IOException e) {
			br=null;
			dict = null;
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			br = null;
		}
	}

	public Set<String> listCoreWords() {
		if ( dict == null ){
			return null;
		}
		return new HashSet<String>(dict.keySet());
	}

	public Collection<Entry> listEntry() {
		if ( dict == null ){
			return null;
		}
		return dict.values();
	}

	public Entry lookup(String entry) {
		if ( dict == null ){
			return null;
		}
		return dict.get(entry);
	}
	
	public void setEntryProcesser(EntryProcesser entryProcesser) {
		this.entryProcesser = entryProcesser;
	}

	public void setEntryTemplate(Map<String, Integer> entryTemplate) {
		this.entryTemplate = entryTemplate;
	}

	public void setDictionarySize(int dictionarySize) {
		this.dictionarySize = dictionarySize;
	}

	public void setCorpusPath(String corpusPath) {
		this.corpusPath = corpusPath;
	}

}
